package main

import (
	"3nets.io/wireguardcommon"
	"crypto/sha256"
	"encoding/base64"
	"flag"
	"fmt"
	"golang.org/x/crypto/curve25519"
	"log"
)

func main() {
	seedPtr := flag.String("seed", "", "A seed to use for ECDH generation, encoded as a BASE64 String")
	managerDHPublicPtr := flag.String("managerDHPublic", "", "The public component of 3nets manager dh to be used for wg shared key")
	peeripPtr := flag.String("peerip", "", "The ip address of 3nets manager to use for wg endpoint")
	peerportPtr := flag.String("peerport", "", "The udp port of 3nets manager to use for wg endpoint")

	flag.Parse()
	fmt.Println("seed=", *seedPtr)
	fmt.Println("managerDHPublic=", *managerDHPublicPtr)
	fmt.Println("peerip=", *peeripPtr)
	fmt.Println("peerport=", *peerportPtr)
	var publicKey []byte
	var seedBytes [32]byte
	var err error

	if *seedPtr != "" {
		seedBytes = sha256.Sum256([]byte(*seedPtr))
	} else {
		seedBytes = sha256.Sum256([]byte("3netsedge.io"))
	}
	//create a curve25519 privatekey
	seedBytes[0] &= 248
	seedBytes[31] &= 127
	seedBytes[31] |= 64
	privateKey := base64.StdEncoding.EncodeToString(seedBytes[:])
	fmt.Printf("privateKey = %s\n", privateKey)

	// build publickey from privatekey
	publicKey, err = curve25519.X25519(seedBytes[:], curve25519.Basepoint)
	if err != nil {
		log.Fatalf("curve25519.X25519() failed: %v", err)
	}
	publicKeyStr := base64.StdEncoding.EncodeToString(publicKey)
	fmt.Printf("publicKey  = %s\n", publicKeyStr)

	if *managerDHPublicPtr != "" {
		presharedkey, edgePublic, err := wireguardcommon.GenPskOnEdge(*managerDHPublicPtr)
		if err != nil {
			fmt.Printf("Failed to generate edge presharedkey: %s\n", err)
		} else {
			fmt.Printf("presharedkey = %s\n", presharedkey)
			fmt.Printf("edgePublic = %s\n", edgePublic)
		}
	}
}
